package com.hoongs.v1.filter;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hoongs.v1.entity.LoginUser;
import com.hoongs.v1.utils.JwtUtil;
import com.hoongs.v1.utils.RedisUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

// 实现 springboot 提供的过滤器
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisUtil redisUtil;

    @Value("${whiteList}")
    String whiteLists[];

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        Set<String> whiteList = new HashSet<>();
        for (String url : whiteLists) {
            whiteList.add(url);
        }

        // 获取当前请求路径
        String requestURI = request.getRequestURI().replace("/api/v1", "");

        if (whiteList.contains(requestURI)) {
            filterChain.doFilter(request, response);
            return;
        }

        // 1. 获取token
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            filterChain.doFilter(request, response);
            return;
        }
        // 2. 解析token
        String userId;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userId = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("无效token");
        }

        // 3. 从redis中获取用户信息
        String redisKey = "login:" + userId;
        // 不知道为什么存在序列化问题
        // LoginUser loginUser = redisUtil.getCacheObject(redisKey);

        Object loginUserStr = redisUtil.getCacheObject(redisKey);
        if (Objects.isNull(loginUserStr)) {
            throw new RuntimeException("登录失效");
        }
        LoginUser loginUser = JSONObject.parseObject(redisUtil.getCacheObject(redisKey).toString(), LoginUser.class);

        // 4. 存入 SecurityContextHolder
        // TODO 获取权限信息封装到Authentication 使用三个参数，标志已认证
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

        filterChain.doFilter(request, response);

    }
}
